const gulp = require("gulp");
const cssmin = require("gulp-cssmin");
const autoprefixer = require("gulp-autoprefixer");
const babel = require("gulp-babel");
const uglify = require("gulp-uglify");
const htmlmin = require("gulp-htmlmin");
const sass = require("gulp-sass-china");
const webserver = require("gulp-webserver");

function sassFn(){
    return gulp.src("./project/css/**/*")
    .pipe(sass())
    .pipe(autoprefixer("last 2 versions", "safari 5", "ie 8", "ie 9", "opera 12.1", "ios 6", "android 4")).pipe(cssmin()).pipe(gulp.dest("./server/css"))
}
function dataFn(){
    return gulp.src("./project/data/**/*").
    pipe(gulp.dest("./server/data"));
}
function phpFn(){
    return gulp.src("./project/php/**/*").
    pipe(gulp.dest("./server/php"));
}
function jsFn(){
    return gulp.src("./project/js/**/*").
        pipe(babel({
            presets: ["@babel/env"]
        }
        ))
        .pipe(uglify()).pipe(gulp.dest("./server/js"));
}
// function jsFn(){
//     return gulp.src("./project/js/**/*").
//     pipe(gulp.dest("./server/js"));
// }
function indexFn() {
    return gulp.src("./project/index.html").pipe(gulp.dest("./server"));
}
function staticFn() {
    return gulp.src("./project/static/**/*").pipe(gulp.dest("./server/static"));
}
function htmlFn() {
    return gulp.src("./project/pages/**/*")
        .pipe(htmlmin({
            removeEmptyAttributes: true,
            collapseWhitespace: true
        }))
        .pipe(gulp.dest("./server/pages"))
}
function watchAll(next) {
    gulp.watch("./project/static/**/*", staticFn);
    gulp.watch("./project/js/**/*", jsFn);
    gulp.watch("./project/index.html", indexFn);
    gulp.watch("./project/pages/**/*", htmlFn);
    gulp.watch("./project/css/**/*", sassFn);
    gulp.watch("./project/data/**/*", dataFn);
    gulp.watch("./project/php/**/*", phpFn);
    next();
}
function server(){
    return gulp.src("./server").pipe(webserver({
        host:"localhost",
        port:"1000",
        livereload:true,
        open:"./index.html"
    }))
}
// exports.listen=watchAll;
exports.listen=gulp.series(staticFn,jsFn,sassFn,indexFn,phpFn,dataFn,htmlFn,watchAll);
exports.all=gulp.series(
    gulp.parallel(staticFn,jsFn,sassFn,indexFn,htmlFn,phpFn,dataFn),
    gulp.parallel(watchAll,server)
);